package tjtt.common.exception;

import tjtt.common.BaseResult;
import tjtt.common.utils.MyBeanUtils;
import tjtt.common.utils.StringUtil;
import tjtt.common.enums.ExceptionEnum;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.sql.SQLException;

/**
 * @Author: luoyi
 * @Description: 全局异常解决方案
 * @Date: 16:13 2017/8/14
 * @Version: 1.0.0
 * @Modified By: xxx
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        int statusCode = 200;
        String message = "";
        if(e instanceof SQLException){
            statusCode = ExceptionEnum.SQLException.getStatus();
        }else if(e instanceof NullPointerException){
            statusCode =ExceptionEnum.NullPointerException.getStatus();
        }else if(e instanceof LoginExpiredException){
            statusCode = ExceptionEnum.LoginExpiredException.getStatus();
            message = ExceptionEnum.LoginExpiredException.getName();
        }else if(e instanceof EmptyDataException){
            statusCode = ExceptionEnum.EmptyDataException.getStatus();
            message = ExceptionEnum.EmptyDataException.getName();
        }else if(e instanceof FileNotFoundException){
            statusCode = ExceptionEnum.FileNotFoundExcetion.getStatus();
            message = ExceptionEnum.FileNotFoundExcetion.getName();
        }else {
            statusCode = ExceptionEnum.OtherException.getStatus();
        }

        if (StringUtil.IsNullOrEmpty(message)){
            message = ExceptionEnum.OtherException.getName();
        }
        View view = new MappingJackson2JsonView();
        ModelAndView mv = new ModelAndView(view, MyBeanUtils.beanToMap(BaseResult.onError(statusCode,message)));
        return mv;
    }
}
